package com.lucy.disk.minio.provider;

import cn.hutool.core.lang.Validator;
import com.lucy.disk.constant.DiskConst;
import com.lucy.disk.domain.entity.FileEntity;
import com.lucy.disk.loader.StorageServiceLoader;
import com.lucy.disk.minio.utils.MinioUtil;
import com.lucy.disk.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Optional;

/**
 * @author kindear
 * 存储服务 MinIO实现
 */
@Primary
@Slf4j
@Service("v1")
public class StorageServiceProvider implements StorageServiceLoader {
    @Autowired
    MinioUtil minioUtil;

    @Autowired
    FileService fileService;

    @Override
    public String uploadFile(MultipartFile file, String fileName) throws Exception {
        minioUtil.uploadFile(file, DiskConst.DEFAULT_OSS_BUCKET_NAME,fileName);
        return fileName;
    }

    @Override
    public String uploadFile(MultipartFile file, String bucketName, String fileName) throws Exception {
        if (Validator.isEmpty(bucketName)){
            bucketName = DiskConst.DEFAULT_OSS_BUCKET_NAME;
        }
        minioUtil.uploadFile(file, bucketName,fileName);
        return fileName;
    }

    @Override
    public InputStream downloadFile(String fileKey) throws Exception {
        return minioUtil.getObject(DiskConst.DEFAULT_OSS_BUCKET_NAME,fileKey);
    }

    @Override
    public InputStream downloadFile(String bucketName, String fileKey) throws Exception {
        if (Validator.isEmpty(bucketName)){
            bucketName = DiskConst.DEFAULT_OSS_BUCKET_NAME;
        }
        return minioUtil.getObject(bucketName,fileKey);
    }

    @Override
    public boolean deleteFile(String fileKey) throws Exception {
        // 移除存储对象
        minioUtil.removeObject(DiskConst.DEFAULT_OSS_BUCKET_NAME,fileKey);
        return true;
    }

    @Override
    public boolean deleteFile(String bucketName, String fileKey) throws Exception {
        if (Validator.isEmpty(bucketName)){
            bucketName = DiskConst.DEFAULT_OSS_BUCKET_NAME;
        }
        minioUtil.removeObject(bucketName,fileKey);
        return true;
    }

    @Override
    public boolean updateFile(InputStream stream, String fileKey) throws Exception {
        FileEntity file = fileService.getOneUnwrap(fileKey);
        String bucketName = file.getBucketName();
        if (Validator.isEmpty(bucketName)) {
            bucketName = DiskConst.DEFAULT_OSS_BUCKET_NAME;
        }
        minioUtil.putObject(bucketName,file.getOssUrl(),stream);
        return true;
    }

}
